package gweb

import (
	"os"
	"time"

	"go.uber.org/zap"
)

// 基础模型
type Model struct {
	ID        uint       `gorm:"primarykey" json:"id"`
	CreatedAt *time.Time `gorm:"not null;default:CURRENT_TIMESTAMP(3);comment:创建时间" json:"created_at,omitempty"`
	UpdatedAt *time.Time `gorm:"default:NULL on update CURRENT_TIMESTAMP(3);comment:更新时间" json:"updated_at,omitempty"`
	DeletedAt *time.Time `gorm:"index" json:"deleted_at,omitempty"`
}

// 注册数据模型
func (app *GinApp) RegisterModels(models ...any) {
	app.Models = append(app.Models, models...)
}

// 迁移数据模型
func (app *GinApp) MigrateDbModels() {
	models := app.Models
	app.DB.DisableForeignKeyConstraintWhenMigrating = true
	err := app.DB.AutoMigrate(models...)
	if err != nil {
		app.logger.Error("register table failed", zap.Error(err))
		os.Exit(0)
	}
	app.DB.DisableForeignKeyConstraintWhenMigrating = false
	err = app.DB.AutoMigrate(models...)
	if err != nil {
		app.logger.Error("register table failed", zap.Error(err))
		os.Exit(0)
	}
	app.logger.Info("register table success")
}
